package com.example;


import io.netty.channel.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.ScheduledFuture;

import java.util.concurrent.TimeUnit;

@ChannelHandler.Sharable
public class ClientHandler extends ChannelInboundHandlerAdapter {
    private NettyStarter nettyStarter;

    public ClientHandler(NettyStarter nettyStarter) {
        this.nettyStarter = nettyStarter;
    }

    private Channel channel;

//    public static final String HEART_BEAT = "*0036H00001A000000000012020011120000012.5#";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("接收到消息:{}"+ msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与服务端断开连接，即将重连...");
        final EventLoop eventLoop = ctx.channel().eventLoop();
        eventLoop.schedule(new Runnable() {
            @Override
            public void run() {
                nettyStarter.doConnect();
            }
        }, 5L, TimeUnit.SECONDS);
        super.channelInactive(ctx);
    }

    /**
     * 空闲心跳机制
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.WRITER_IDLE) {// 写空闲时发心跳
                System.out.println("发送心跳");
                ctx.writeAndFlush(new ResMsg(MsgTypeEnum.REQ_HEART,"7FD8F5BDA6734FA7A92DB9CA5180FB97","{}").getMsgBody());
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("========1===");
        super.channelActive(ctx);
//        定时心跳机制
        this.channel = ctx.channel();
        ping(ctx.channel());
    }

    private void ping(Channel channel) {
        ScheduledFuture<?> future = channel.eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                if (channel.isActive()) {
                    System.out.println("======发送===");
                    channel.writeAndFlush(new ResMsg(MsgTypeEnum.REQ_HEART,"7FD8F5BDA6734FA7A92DB9CA5180FB97","{}").getMsgBody());
                } else {
                    channel.closeFuture();
                    throw new RuntimeException();
                }
            }
        }, 10L, TimeUnit.SECONDS);
        future.addListener(new GenericFutureListener() {
            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()) {
                    ping(channel);
                }
            }
        });
    }
}
